package com.thinkgem.jeesite.modules.sys.web;

import com.thinkgem.jeesite.common.annotation.MobileApi;
import com.thinkgem.jeesite.common.exception.MobileApiException;
import com.thinkgem.jeesite.common.exception.UserAuthorizationException;
import com.thinkgem.jeesite.common.utils.BeanUtilEx;
import com.thinkgem.jeesite.common.utils.JedisUtils;
import com.thinkgem.jeesite.common.utils.TicketConfig;
import com.thinkgem.jeesite.common.utils.TicketUtils;
import com.thinkgem.jeesite.common.web.BaseMobileApiController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.sys.vo.LoginResponse;
import com.thinkgem.jeesite.modules.sys.vo.LoginUserVo;
import com.thinkgem.jeesite.modules.sys.vo.LoginVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by admin on 2017-12-5.
 */
@MobileApi
@Controller
@RequestMapping("/mobile-api")
public class MobileApiLoginController extends BaseMobileApiController {

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public LoginResponse login(@RequestBody LoginVo loginVo) {
        logger.debug(loginVo.toString());
        User currentUser = UserUtils.getByLoginName(loginVo.getLoginName());
        if (currentUser == null) {
            throw new MobileApiException("用户不存在");
        }
        // 登录成功
        if (SystemService.validatePassword(loginVo.getPassword(), currentUser.getPassword())) {
            // 删除已经存在的ticket
            String userTicketKey = TicketConfig.KEY_USERTK + currentUser.getId();
            if (JedisUtils.exists(userTicketKey)) {
                String ticketOld = JedisUtils.get(userTicketKey);
                JedisUtils.del(TicketConfig.KEY_TKUSER + ticketOld);
                JedisUtils.del(userTicketKey);
            }
            String ticket = TicketUtils.generate(currentUser.getId());
            JedisUtils.set(TicketConfig.KEY_TKUSER + ticket, currentUser.getId(), TicketConfig.EXPIRE_TIME_7_DAYS);
            JedisUtils.set(userTicketKey, ticket, TicketConfig.EXPIRE_TIME_7_DAYS);
            LoginUserVo loginUserVo = new LoginUserVo();
            BeanUtilEx.copyProperties(loginUserVo, currentUser);
            return new LoginResponse(ticket, loginUserVo);
        } else {
            throw new MobileApiException("密码不正确");
        }

    }

}
